package com.itvita.code.generator.config;

import com.itvita.code.generator.constant.DbDriver;
import com.itvita.code.generator.entity.model.DataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.DriverManager;

/**
 * @Time: 2021/1/22 11:22 上午
 * @author: liu.q [916000612@qq.com]
 * @des:  JdbcTemplate 链接数据源配置
 * */
public class JdbcTemplateConfig {

    public static JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();

        for (DbDriver dbDriver : DbDriver.values()) {
            if (dbDriver.toString().equals(dataSource.getType())) {
                dataSourceBuilder.driverClassName(dbDriver.getDriver());
                dataSourceBuilder.url(dbDriver.getUrl(dataSource.getHost(), dataSource.getPort(), dataSource.getDatabase()));
                break;
            }
        }
        dataSourceBuilder.username(dataSource.getUserName());
        dataSourceBuilder.password(dataSource.getPassword());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceBuilder.build());
        return jdbcTemplate;
    }

    public static String testConnection(DataSource dataSource) {
        try {
            String url = "";
            if (DbDriver.MYSQL.toString().equals(dataSource.getType())) {
                Class.forName(DbDriver.MYSQL.getDriver());
                url = DbDriver.MYSQL.getUrl(dataSource.getHost(), dataSource.getPort(), dataSource.getDatabase());
            }
            DriverManager.getConnection(url, dataSource.getUserName(), dataSource.getPassword());
            return "OK";
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
